<template>
  <layout :title="`${isLarge ? '大户' : '农户'}信息汇总浏览表`">
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button class="action-button" type="primary" icon="search" @click="search()"
          >搜索</a-button
        >
        <!-- <a-button
          class="action-button"
          type="primary"
          @click="handlerTableAdd"
        >新增农户</a-button> -->
        <a-button
          class="action-button"
          type="default"
          @click="tableExportExecl()"
          >按搜索条件导出电子表（模板）</a-button
        >
      </custom-form>
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="(record) => record.s_a_id"
      :pagination="false"
      :loading="tableLoading"
      @change="handleTableChange"
      :customRow="customTableRow"
      class="table-total"
      :scroll="{
        y: tableClientHeight + 70,
        x: '100%',
      }"
      bordered
    >
      <!-- 自定义表头 -->
      <template slot="pay_price"> 补贴标准<br />(亩/元) </template>

      <template slot="pay_unit_title"> 补贴核算依据 </template>

      <template slot="used_percent" slot-scope="row">
        {{
          (!row.bt_member_total || row.bt_member_total === '0'
            ? 0
            : (+row.used / +row.bt_member_total) * 100
          ).toFixed(2)
        }}%
      </template>
      <template slot="un_used" slot-scope="row">
        {{ !row.bt_member_total ? 0 : +row.bt_member_total - +row.used }}
      </template>
      <template slot="un_used_percent" slot-scope="row">
        {{
          (!row.bt_member_total || row.bt_member_total === '0'
            ? 0
            : ((+row.bt_member_total - +row.used) / +row.bt_member_total) * 100
          ).toFixed(2)
        }}%
      </template>

      <!-- 补贴总金额（元） -->
      <template slot="pay_price_total" slot-scope="row">
        {{
          (
            (+row.pay_unit === 1 ? row.plant_used || 0 : row.field_used || 0) *
            row.pay_price
          ).toFixed(2)
        }}
      </template>

      <template slot="pay_unit_base" slot-scope="row">
        {{ getLabel(row.pay_unit_base, [], 'pay_unit_base') }}
      </template>

      <template slot="bt_size" slot-scope="row">
        {{ +row.pay_unit === 1 ? row.plant_used || 0 : row.field_used || 0 }}
      </template>

      <template slot="plant" slot-scope="row">
        {{ row.plant || 0 }}
      </template>

      <template slot="pay_unit" slot-scope="row">
        {{ getLabel(row.pay_unit, [], 'pay_unit') }}
      </template>

      <template slot="s_state" slot-scope="row">
        <template>
          <span :style="{ color: (row.s_state === 0 ? '#118e11' : '#f60') }">{{
            getLabel(
              row.s_state ? `${row.s_state}` : row.s_state,
              [],
              's_state'
            ) || '未锁定'
          }}</span>
        </template>
      </template>

      <!-- 按钮区 -->
      <template slot="action" slot-scope="row">
        <template>
          <a-popconfirm
            :title="`您确定是否锁定${
              row.s_a_nam
            }数据?`"
            ok-text="确认"
            cancel-text="取消"
            @confirm="updateSubsidyLockStatus(row.s_a_id, 1)"
          >
            <a-button type="link" size="small">
              [锁定]
            </a-button>
          </a-popconfirm>

          <a-popconfirm
            :title="`您确定是否解锁${
              row.s_a_nam
            }数据?`"
            ok-text="确认"
            cancel-text="取消"
            @confirm="updateSubsidyLockStatus(row.s_a_id, 0)"
          >
            <a-button type="link" :disabled="row.s_a_id.length < 6" size="small">
              [解锁]
            </a-button>
          </a-popconfirm>

          <a-popconfirm
            title="这里要删除的数据无法恢复！您确认要删除该辖区下所有农户数据?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="tableDel(row)"
          >
            <a-button
              type="link"
              class="action-button"
              v-if="!isLarge"
              :auth="{
                keys: ['member.area-delete', !(row.s_a_id.length < 9)],
                relate: 'and',
              }"
              size="small"
              >删除辖区未补农户</a-button
            >
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <!-- <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :show-total="showTotal"
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination> -->

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      :footer="null"
      centered
      @cancel="visible = false"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
      <!-- <section slot="footer"> -->
      <a-button type="primary" @click="handleSubmit">提交</a-button>
      <!-- </section> -->
    </a-modal>
  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { PayUnitType } from '@/common/enum'
import { famerServices } from '@/common/services/famer'
import { userModule } from '@/store/modules/user'
import { largeMemberServices } from '@/common/services/largeMember'
import subsidyServices from '@/common/services/subsidy'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
  },
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: String,
  })
  public currentAreaId!: string

  public commonParams = {
    s_a_id: '',
  }

  get isLarge() {
    return userModule.isLarge
  }

  public hasTotalRow = true

  public isLocalSort = true

  // 产品列表搜索条件
  public tableSearch = {
    is_used: '',
    s_state: '',
    switch: '1',
  }

  // 产品列表表格信息
  get customColumns() {
    return [
      {
        title: '加入补贴状态',
        dataIndex: 'is_used',
        key: 'is_used',
        width: 140,
        form: {
          type: 'a-radio-group',
          placeholder: '请选择补贴状态',
          isShowList: false,
          isShowQuery: true,
          dict: [
            {
              label: '已加入',
              value: '1',
            },
            {
              label: '未加入',
              value: '2',
            },
          ],
        },
      },
      {
        title: '是否加入公示',
        dataIndex: 'is_pub',
        key: 'is_pub',
        width: 140,
        form: {
          type: 'a-radio-group',
          placeholder: '请选择补贴状态',
          isShowList: false,
          isShowQuery: true,
          dict: [
            {
              label: '已加入',
              value: '1',
            },
            {
              label: '未加入',
              value: '2',
            },
          ],
        },
      },
      {
        title: '行政编码',
        dataIndex: 's_a_id',
        key: 's_a_id',
        width: 130,
        form: {
          type: 'a-input',
          placeholder: '编号自动生成',
          disabled: true,
        },
      },
      {
        title: '行政区',
        dataIndex: 's_a_nam',
        key: 's_a_nam',
        width: 140,
        form: {
          type: 'a-input',
          placeholder: '请输入行政区名称',
        },
      },
      {
        title: '农户总数',
        dataIndex: 'member_total',
        key: 'member_total',
        align: 'right',
        width: 120,
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        form: {
          type: 'a-textarea',
          placeholder: '请输入家庭住址',
        },
      },
      {
        title: '应享补贴(户)',
        dataIndex: 'bt_member_total',
        key: 'bt_member_total',
        align: 'right',
        width: 120,
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        form: {
          type: 'a-textarea',
          placeholder: '请输入家庭住址',
        },
      },
      {
        title: '已享受补贴',
        key: 'used',
        children: [
          {
            title: '户数',
            dataIndex: 'used',
            key: 'used',
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            align: 'right',
            width: 80,
          },
          {
            title: '占比%',
            scopedSlots: { customRender: 'used_percent' },
            key: 'used_percent',
            align: 'right',
            width: 80,
          },
        ],
      },

      {
        title: '未享受补贴',
        key: 'un_used',
        children: [
          {
            title: '户数',
            width: 80,
            align: 'right',
            // sorter: true,
            // sortDirections: ['ascend', 'descend'],
            scopedSlots: { customRender: 'un_used' },
            key: 'un_used',
          },
          {
            title: '占比%',
            width: 80,
            align: 'right',
            scopedSlots: { customRender: 'un_used_percent' },
            key: 'un_used_percent',
          },
        ],
      },

      {
        title: '耕地面积（实际耕种面积，亩）',
        key: 'field',
        children: [
          ...(this.isLarge
            ? []
            : [
                {
                  title: '基础面积依据',
                  scopedSlots: { customRender: 'pay_unit_base' },
                  align: 'center',
                  width: 110,
                  key: 'pay_unit_base',
                  form: {
                    type: 'a-select',
                    placeholder: '请选择基础面积依据',
                    isShowFrom: false,
                    isExport: false,
                    dict: PayUnitType,
                  },
                },
              ]),
          {
            title: this.isLarge ? '承包地' : '基础面积',
            dataIndex: 'field1',
            key: 'field1',
            width: 120,
            align: 'right',
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入确权总面积',
              renderMode: ['farmland'],
            },
          },
          {
            title: '增加面积',
            dataIndex: 'field2',
            align: 'right',
            key: 'field2',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入确权总面积',
              renderMode: ['farmland'],
            },
          },
          {
            title: '减少面积',
            dataIndex: 'field3',
            align: 'right',
            key: 'field3',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入确权总面积',
              renderMode: ['farmland'],
            },
          },
          {
            title: '小计',
            dataIndex: 'field',
            key: 'field',
            align: 'right',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入确权总面积',
              renderMode: ['farmland'],
            },
          },
        ],
      },
      ...this.areaField,
      {
        title: '补贴面积',
        width: 110,
        dataIndex: 'pay_size_total',
        align: 'right',
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        // scopedSlots: { customRender: 'bt_size' },
        key: 'pay_size_total',
      },
      {
        // title: '补贴标准(亩/元)',
        titleAlias: '补贴标准(亩/元)',
        slots: { title: 'pay_price' },
        width: 80,
        dataIndex: 'pay_price',
        align: 'right',
        key: 'pay_price',
      },
      // {
      //   title: '参与补贴的确权面积',
      //   width: 110,
      //   dataIndex: 'field_used',
      //   align: 'right',
      //   sorter: true,
      //   sortDirections: ['ascend', 'descend'],
      //   key: 'field_used'
      // },
      {
        title: '补贴金额',
        key: 'pay_price_total',
        dataIndex: 'pay_price_total',
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        // scopedSlots: { customRender: 'pay_price_total' },
        align: 'right',
        width: 120,
      },
      {
        title: '上报锁定',
        key: 's_state',
        // dataIndex: 's_state',
        width: 100,
        fixed: 'right',
        scopedSlots: { customRender: 's_state' },
        form: {
          type: 'a-select',
          placeholder: '请选择',
          isShowQuery: false,
          isExport: false,
          dict: [
            {
              label: '未锁定',
              value: '0',
            },
            {
              label: '区县已锁定',
              value: '1',
            },
            {
              label: '乡镇已锁定',
              value: '2',
            },
            {
              label: '村已锁定',
              value: '3',
            },
            {
              label: '社已锁定',
              value: '4',
            },
          ],
        },
      },

      // 搜索专用
      {
        title: '上报锁定',
        key: 's_state',
        // dataIndex: 's_state',
        width: 100,
        fixed: 'right',
        scopedSlots: { customRender: 's_state' },
        form: {
          type: 'a-radio-group',
          placeholder: '请选择',
          isShowQuery: true,
          isShowList: false,
          isShowFrom: false,
          dict: [
            {
              label: '未锁定',
              value: '0',
            },
            {
              label: '已锁定',
              value: '1',
            },
          ],
        },
      },

      {
        title: '操作',
        key: 'action',
        width: this.isLarge ? 90 : 210,
        fixed: 'right',
        scopedSlots: { customRender: 'action' },
      },
    ]
  }

  public tableApi = {
    list: this.isLarge
      ? largeMemberServices.getLargeMemberDetail
      : famerServices.getMemberList,
    exportExecl: this.isLarge
      ? largeMemberServices.exportExecl
      : famerServices.exportExecl,
    // add: famerServices.updateMemberGrain,
    // edit: famerServices.updateMemberGrain
    del: famerServices.deleteMemberFromArea,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.columns = this.customColumns
    this.getData()
  }

  get isDistrictUser() {
    return false // || this.currentAreaId.length >= 6
  }

  get areaField() {
    return !this.isDistrictUser
      ? [
          ...((true || this.isLarge)
            ? []
            : [
                {
                  title: '确权面积（亩）',
                  align: 'right',
                  dataIndex: 'field_confirm_t',
                  sorter: true,
                  sortDirections: ['ascend', 'descend'],
                  width: 100,
                  key: 'field_confirm_t',
                },
                {
                  title: '二包面积（亩）',
                  align: 'right',
                  dataIndex: 'field_confirm',
                  sorter: true,
                  sortDirections: ['ascend', 'descend'],
                  width: 100,
                  key: 'field_confirm',
                },

                {
                  title: '计税面积（亩）',
                  align: 'right',
                  sorter: true,
                  sortDirections: ['ascend', 'descend'],
                  width: 100,
                  dataIndex: 'field_tax',
                  key: 'field_tax',
                },
              ]),
          // {
          //   title: '粮食种植面积（亩）',
          //   width: 130,
          //   align: 'right',
          //   sorter: true,
          //   sortDirections: ['ascend', 'descend'],
          //   scopedSlots: { customRender: 'plant' },
          //   key: 'plant',
          // },
          // {
          //   // title: '补贴参照(补贴核算依据)',
          //   titleAlias: '补贴面积计算依据',
          //   slots: { title: 'pay_unit_title' },
          //   width: 130,
          //   key: 'pay_unit',
          //   align: 'center',
          //   scopedSlots: { customRender: 'pay_unit' },
          //   form: {
          //     type: 'a-select',
          //     placeholder: '请选择补贴核算依据',
          //     isShowFrom: false,
          //     dict: PayUnitType,
          //   },
          // },
        ]
      : []
  }

  public mounted() {}

  public async getData() {
    this.tableData = []
    const res = await this.getTableList()
    console.log('res', res)
  }

  public handlerTableAdd() {
    this.tableAdd()
    this.$nextTick(() => {
      this.currentRow = Object.assign(
        {},
        { s_a_id: this.currentAreaId, role: 1 }
      )
    })
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: any) {
    this.tableEdit(Object.assign({}, row))
  }

  // 更新区域补贴锁定状态
  public updateSubsidyLockStatus(id: string, status: number) {
    subsidyServices
      .updateSubsidyLockStatus({
        s_a_id: id,
        s_state: +status,
      })
      .then((_) => {
        this.getData()
        this.$message.success('状态更新成功')
      })
  }
}
</script>

<style scoped lang="less">
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
/deep/ .ant-table {
  th[key='member_total'],
  th[key='plant'],
  th[key^='pay'],
  th[key='pay_price_total'] {
    text-align: center !important;
  }

  thead tr {
    background: #fafafa;
  }

  tbody tr {
    background: #fff;
  }

  th[key='s_a_nam'],
  tr td:nth-of-type(3) {
    position: sticky;
    left: 0;
    z-index: 3;
    background: inherit;
  }
}
// /deep/ .ant-table-thead th {
//   text-align: center!important;
// }
</style>
